#include "recvFile.h"

int recvn(int netfd, void *buf, long total) {
    //char的基本操作单位为一个字节
    char *p = (char*)buf;
    long cursize = 0;
    while(cursize < total) {
        ssize_t sret = recv(netfd, p + cursize, total - cursize, 0);
        cursize += sret;
    }
    return 0;
}

int recvFile(int netfd) {
    char fileName[SELFFILENAME_MAX] = {0}; 
    train_t train;
    //先接受文件名,再接受文件大小,最后循环接受文件数据
    //先接受文件大小,明确信息边界,再接受数据
    recvn(netfd, &train.len, sizeof(train.len)); 
    recvn(netfd, train.data, train.len);
    memcpy(fileName, train.data, train.len);

    //创建文件
    int fd = open(fileName, O_CREAT | O_RDWR | O_TRUNC, 0666);

    off_t fileSize;
    recvn(netfd, &train.len, sizeof(train.len));
    recvn(netfd, train.data, train.len);
    memcpy(&fileSize, train.data, train.len);

    //进度条
    off_t cursize = 0;
    off_t lastsize = 0;
    off_t slice = fileSize / 100;

    while(1) {
        recvn(netfd, &train.len, sizeof(train.len));
        recvn(netfd, train.data, train.len);
        write(fd, train.data, train.len);
        //收到空包
        if(train.len == 0) {
            break;
        }
        cursize += train.len;
        if(cursize - lastsize > slice) {
            printf("download progress bar:%5.2f%%\r", cursize * 100.0 / fileSize);
            fflush(stdout);
            lastsize = cursize;
        }
    }

    printf("download progress bar:100.00%%\n");
    return 0;
}
